import { Parser } from "expr-eval";

const parser = new Parser({
  operators: {
    add: true,
    subtract: true,
    multiply: true,
    divide: true,
    power: true,
    logical: true,
    comparison: true,
    concatenate: true
  }
});

export function safeEvaluate(expression: string, scope: Record<string, any>) {
  const expr = parser.parse(expression || "");
  const vars = expr.variables();
  for (const v of vars) {
    if (!Object.prototype.hasOwnProperty.call(scope, v)) {
      throw new Error(`Disallowed variable: ${v}`);
    }
  }
  return expr.evaluate(scope);
}
